package handler

import (
	"encoding/json"
	"fan-ctrl-sys/cache"
	"fan-ctrl-sys/models"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var list []models.Post
	redis_list_key := "redis_list_" + strconv.Itoa(page)
	listData, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if listData == "" {
		models.DB.Offset(offset).Limit(size).Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(listData), &list)
	}
	var total int64
	models.DB.Model(&models.Post{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  500,
		"msg":   "查询成功",
		"data":  list,
		"total": total,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var post models.Post
	redis_list_key := "redis_list_" + id
	listData, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if listData == "" {
		models.DB.Where("id = ?", id).Find(&post)
		jsonData, _ := json.Marshal(post)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(listData), &post)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": post,
	})
	return
}
